import {
    BASE_URL
} from '../../../http/config';
Page({

    data: {
        article: [], // 存储分类及商品数
        pageNum: 1,
        pageSize: 1,
        count: [],
        loading: false,
        img:''
    },

    onLoad() {
        this.getCategoryList();
    },

    // 获取全部分类
    getCategoryList() {
        wx.request({
            url: `${BASE_URL}/TestClassify/findPage`,
            method: "GET",
            success: (res) => {
                if (res.data.code === 200) {
                    const categories = res.data.data.list;
                    this.setData({
                        article: categories
                    });
                    this.getProductCounts(categories);
                }
            }
        });
    },

    // 获取每个分类的商品数量（优化版）
    getProductCounts(categories) {
        // 1. 创建去重后的ID列表
        const uniqueIds = [...new Set(categories.map(item => item.id))];

        // 2. 使用Promise.all并行请求
        const requests = uniqueIds.map(id => {
            return new Promise((resolve) => {
                wx.request({
                    url: `${BASE_URL}/TestClassify/findTestCount/${id}`,
                    method: "GET",
                    success: (res) => {
                        if (res.data.code === 200) {
                            resolve({
                                id,
                                count: res.data.data
                            });
                        } else {
                            resolve({
                                id,
                                count: 0
                            }); // 失败时默认0
                        }
                    },
                    fail: () => resolve({
                        id,
                        count: 0
                    }) // 失败时默认0
                });
            });
        });

        // 3. 等待所有请求完成
        Promise.all(requests).then(results => {
            // 4. 创建ID到数量的映射
            const countMap = {};
            results.forEach(item => {
                countMap[item.id] = item.count;
            });

            // 5. 更新article数组
            const updatedArticle = this.data.article.map(item => ({
                ...item,
                count: countMap[item.id] || 0
            }));

            // 6. 一次性更新UI
            this.setData({
                article: updatedArticle
            });
        });
    }
});